var map;
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();

$(document).ready(function(){
	map = new google.maps.Map(document.getElementById("map_canvas"),{
		zoom: 12,
		center: new google.maps.LatLng(1.3603333, 103.8133333),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	
	$("#dialogmap" ).dialog({ width: 930 });

	$('.route').each(function(){
		var thisRoute = $(this);
		var waypoints = [];
		thisRoute.children('.routePoint').each(function(index){
			var lat = parseFloat($(this).children('.lat').first().html());
			var lng = parseFloat($(this).children('.lng').first().html());
			var title = $(this).children('.title').first().html();
			var address = $(this).children('.address').first().html();
			var latLng = new google.maps.LatLng(lat,lng);
			waypoints.push({ location: address, stopover: true });
		});
		var startPoint = waypoints.shift();
		var endPoint = waypoints.pop();
		var request = {
			origin: startPoint.location, 
			destination: endPoint.location,
			waypoints: waypoints,
			optimizeWaypoints: true,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		directionsService.route(request, function(result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				var directionsRenderer = new google.maps.DirectionsRenderer({ preserveViewport:true });
				//directionsRenderer.setMap(map);
				directionsRenderer.setDirections(result);
				(function(directionsRenderer){
					thisRoute.children('.routeButton').click(function(){
						directionsRenderer.setMap(map);
						$("#dialogmap").dialog('open');
					});
					$("#dialogmap").bind("dialogclose", function(event, ui) {
						directionsRenderer.setMap(null);
					});
				})(directionsRenderer);
			}
		});
	});
});